package TCP.case3;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class RedisClient {
    private static Scanner scanner=new Scanner(System.in);
    private static PrintWriter writer;
    private static BufferedReader reader;
    public static void main(String[] args) {
        //与redis服务器建立连接
        try(Socket socket=new Socket("122.112.217.206",6381)) {
            //获取输入输出流
             writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
             reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //等待输入命令
            while (true) {
                String cmdline = scanner.nextLine();
                if("exit".equals(cmdline))break;
                //输入输出
                //输入
                sendRequest(cmdline);
                //输出
                Object o = handleResponse();
                System.out.println(o);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static Object handleResponse() throws IOException {
        int flag = reader.read();
        switch (flag){
            case '+'://单行字符串直接读一行
                return reader.readLine();
            case '-'://异常信息也读一行
                return new RuntimeException("e:"+reader.readLine());
            case ':'://数字
                return Long.parseLong(reader.readLine());
            case '$'://读可能含有特殊字符的字符串
                int len = Integer.parseInt(reader.readLine());
                if(len==-1)return null;
                if(len==0)return "";
                //假设中间没有特殊字符
                return reader.readLine();
            case '*'://数组
                return readArr();
            default:
                throw new RuntimeException("语法错误");
        }

    }

    private static Object readArr() throws IOException {
        Integer len = Integer.parseInt(reader.readLine());
        if(len<=0)return null;
        List<Object>data=new ArrayList<>(len);
        for (Integer i = 0; i < len; i++) {
            data.add(handleResponse());
        }
        return data;
    }

    private static void sendRequest(String cmdline) {
        String[] splits = cmdline.split(" ");
        writer.println("*"+splits.length);
        for (String split : splits) {
            String w = "$" + split.length() + "\r\n" + split;
            writer.println(w);
        }
//        cmdline="$"+cmdline.length()+"\r\n"+cmdline+"\r\n";
//        writer.print(cmdline);
        writer.flush();
    }
}
